package com.mrzhou.web.strategy;

import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.Callable;

/**
 * @author qiang.zhou
 * @des 解决Feign集成Hystrix时在Feign拦截器中获取不到请求参数的问题
 */
public class HystrixConcurrencyRequestContextStrategy extends HystrixConcurrencyStrategy {

    @Override
    public <T> Callable<T> wrapCallable(Callable<T> callable) {
        return new RequestAttributeAwareCallable(callable, RequestContextHolder.getRequestAttributes());
    }

    static class RequestAttributeAwareCallable<T> implements Callable<T> {

        private final Callable<T> callable;
        private final  RequestAttributes requestAttributes;

        RequestAttributeAwareCallable(Callable<T> callable, RequestAttributes requestAttributes) {
            this.callable = callable;
            this.requestAttributes = requestAttributes;
        }

        @Override
        public T call() throws Exception {
            try {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                return callable.call();
            } finally {
                RequestContextHolder.getRequestAttributes();
            }
        }
    }


}
